package com.ycsj.goldmedalnewconcept.teacher.fragment;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.ycsj.common.base.BaseLazyFragment;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.TDialogManager;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.TkKeys;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.bean.AnswerInfo;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;

/**
 * 阅读题型(回答题的子Fragment)
 * Created by Administrator on 2018/12/12 0012.
 */

public class ItemFillingSentenceFragment extends BaseLazyFragment implements View.OnClickListener {

    //题干
    @BindView(R.id.tv_question)
    TextView tvQuestion;
    //显示答案的TextView
    @BindView(R.id.tv_show_answer)
    TextView tvShowAnswer;
    //作答
    @BindView(R.id.tv_own_answer)
    TextView tvOwnAnswer;
    //正确答案
    @BindView(R.id.tv_right_answer)
    TextView tvRightAnswer;
    //解析
    @BindView(R.id.tv_parse_answer)
    TextView tvParseAnswer;
    //展示作答,正确,解析的整体布局
    @BindView(R.id.ll_show_answer)
    LinearLayout llShowAnswer;

    @BindView(R.id.ll_stu_answer)
    LinearLayout llStuAnswer;



    //全校正确率的整体布局
    @BindView(R.id.ll_qxzql)
    LinearLayout llQxzql;
    //全校正确率的TextView
    @BindView(R.id.tv_qxzql)
    TextView tvQxzql;


    //页面的数据模型
    private AnswerInfo answerInfo;

    //当前题目在大题的位置
    private int currPos;

    //当前题目的的正确答案
    private String rihgtAnswer;

    //学生做题0  1学生查看解析 2老师查看题和解析-有人做(全校正确率和小题正确率都显示) 3(习题分析)老师查看题和解析-没人做,对应查看单题
    private int state;


    public static final ItemFillingSentenceFragment newInstance(AnswerInfo info, int questionNum, int state) {
        ItemFillingSentenceFragment itemReadEssayQuestionFragment = new ItemFillingSentenceFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        bundle.putInt("curr", questionNum);
        bundle.putInt("state", state);
        itemReadEssayQuestionFragment.setArguments(bundle);
        return itemReadEssayQuestionFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_item_filling_sentence;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        //获取页面数据
        initIntent();

        //初始化视图状态
        initView();
    }

    /**
     * 获取页面数据
     */
    private void initIntent() {
        answerInfo = (AnswerInfo) getArguments().getSerializable("data");
        //正确答案
        if (null != answerInfo) {
            rihgtAnswer = answerInfo.rightAnswer;
            currPos = getArguments().getInt("curr");
            state = getArguments().getInt("state");
        }
    }

    /**
     * 初始化视图状态
     */
    public void initView() {

        if (state == 0) {
            //学生未答题
            llShowAnswer.setVisibility(View.GONE);
            //未完成状态下设置页面数据,包含处理题目的显示以及点击事件的处理等
            initNoCompleteData();

        } else if (state == 1) {
            //学生已答题查看解析
            llShowAnswer.setVisibility(View.VISIBLE);

            //作答不显示
            llStuAnswer.setVisibility(View.VISIBLE);

            //全校正确率显示
            llQxzql.setVisibility(View.GONE);

            initHasCompletedData();

        } else if (state == 2) {
            //老师查看学生解析(有人做)
            llShowAnswer.setVisibility(View.VISIBLE);

            //作答不显示
            llStuAnswer.setVisibility(View.GONE);

            //全校正确率显示
            llQxzql.setVisibility(View.VISIBLE);

            initHasCompletedData();

        } else if (state == 3) {
            //老师查看学生解析(没人做)或查看单题
            llShowAnswer.setVisibility(View.VISIBLE);

            //作答不显示
            llStuAnswer.setVisibility(View.GONE);

            //全校正确率显示
            llQxzql.setVisibility(View.GONE);

            initHasCompletedData();
        }
    }

    /**
     * 做题状态下设置数据
     */
    private void initNoCompleteData() {
        //设置题干
        setQuestionContent();

        //初次进入设置显示答案的TextView的布局参数
        setTvAnswerLayoutParams();
        if("0".equals(AccountUtils.getRole(getActivity()))){
            //未完成列表选项可以点击
            //设置点击事件
            tvShowAnswer.setOnClickListener(this);

        }else{
            //家长不可点击
        }

    }


    /**
     * 设置题干的方法
     */
    private void setQuestionContent() {
        if (answerInfo != null) {
            tvQuestion.setText(answerInfo.qustionContent);
        }
    }

    /**
     * 设置显示答案的TextView的布局参数
     */
    private void setTvAnswerLayoutParams() {
        int padding = UiUtils.dp2px(4);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tvShowAnswer.setPadding(padding, padding, padding, padding);
        tvShowAnswer.setBackgroundResource(R.drawable.question_tv_out_bg);
        tvShowAnswer.setLayoutParams(lp);
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_show_answer) {
            //展示答案的TextView的点击事件
            showInputDialog();
        }
    }

    /**
     * 弹出输入框
     */
    private void showInputDialog() {
        TDialogManager.show(getActivity(),getActivity().getSupportFragmentManager(), R.layout.teacher_app_pop_input_read_essay, 0.3f, new OnBindViewListener() {
            @Override
            public void bindView(BindViewHolder viewHolder) {
                viewHolder.setText(R.id.tv_pop_content, "请输入答案");
                EditText etInput = viewHolder.getView(R.id.et_input);
                etInput.setFilters(new InputFilter[]{new MaxTextLengthFilter(151)});
            }
        }, new OnViewClickListener() {
            @Override
            public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                switch (view.getId()) {
                    case R.id.tv_cancel:
                        TDialogManager.dismiss();
                        break;
                    case R.id.tv_ok:
                        EditText etInput = viewHolder.getView(R.id.et_input);
                        //第一步:获取输入框的文字,进行非空判断
                        String content = etInput.getText().toString().trim();
                        if (TextUtils.isEmpty(content)) {
                            //没有输入单词
                            UiUtils.Toast("您还没有输入单词", false);
                            return;
                        } else {
                            //已经输入了单词
                            //第二步:将输入的单词回显到展示答案的TextView上
                            tvShowAnswer.setText(content);
                            setTvAnswerLayoutParams();

                            //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
                            //currPos对应的每个大题的小题的位置
                            int choosePos = currPos;

                            //用户选的输入的单词
                            String chooseAnswer = content;
                            //是否如正确
                            boolean chooseResult = false;
                            Log.i("test","正确答案："+rihgtAnswer);
                            Log.i("test","输入答案："+content);

                            String temp = rihgtAnswer.trim().toString()
                            .replace(", ",",")
                            .replace(". ",".")
                            .replace("？ ","？")
                            .replace("， ","，")
                            .replace("? ","?")
                            .replace("。 ","。")

                            ;

                            String con = content.replace("/","*");


                            if (isAnswerCorrect(con, temp)) {
                                //用户作答正确
                                chooseResult = true;
                            } else {
                                //用户作答错误
                                chooseResult = false;
                            }
                            BusInfo busInfo = new BusInfo();
                            busInfo.tkMsg = TkKeys.TKMsg;
                            busInfo.tkChoosePos = choosePos;
                            busInfo.tkChooseAnswer = chooseAnswer;
                            busInfo.tkChooseResult = chooseResult;

                            Log.i("test","答案结果："+chooseResult);
                            EventBus.getDefault().post(busInfo);

                            //关闭对话框
                            TDialogManager.dismiss();
                        }

                        break;
                }
            }
        }, R.id.tv_cancel, R.id.tv_ok);
    }

    /**
     * 判断是否作答正确的方法
     * 服务器返回的正确答案中以"/"拼接多个正确答案
     *
     * @param inputContent 用户输入的答案
     * @param rightAnswers 服务器返会的多个正确答案拼接的字符串
     */
    private boolean isAnswerCorrect(String inputContent, String rightAnswers) {
        if (TextUtils.isEmpty(inputContent) || TextUtils.isEmpty(rightAnswers)) {
            return false;
        } else {
            boolean res = false;
            //使用"/"切割服务器返回的正确答案,获取正确答案的数组
            String[] answersGroups = rightAnswers.split("/");

            for (int i = 0; i < answersGroups.length; i++) {
                //去除首尾空格后进行比对
                if (inputContent.trim().equals(answersGroups[i].trim())) {
                    res = true;
                    break;
                }
            }
            return res;
        }

    }
    /**
     * 设置底部的数据
     */
    private void initHasCompletedData() {

        setTvAnswerLayoutParams();

        //设置题干
        setQuestionContent();

        if (state == 1) {
            //学生查看解析

            //设置显示答案的TextView的布局参数
            setTvAnswerLayoutParams();

            //完成状态下设置用户的作答内容
            tvShowAnswer.setText(answerInfo.chooseAnswer);

            if (!TextUtils.isEmpty(answerInfo.chooseAnswer)) {
                tvOwnAnswer.setText(answerInfo.chooseAnswer);
            } else {
                tvOwnAnswer.setText("未作答");
            }
        }

        tvQxzql.setText(answerInfo.proba);

        //正确答案
        tvRightAnswer.setText(answerInfo.rightAnswer);

        //解析
        tvParseAnswer.setText(answerInfo.explain.trim().toString());

    }

}
